package com.springx.examples.showcase.service;

import com.springx.examples.showcase.entity.Organization;
import com.springx.examples.showcase.repository.mybatis.OrganizationMapper;
import com.springx.examples.showcase.vo.tree.ZTreeOrganizationVo;
import com.springx.examples.showcase.vo.tree.ZTreeResourceVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;

/**
 * Created by roman_000 on 2015/8/9.
 */
@Service
@Transactional
public class OrganizationService extends BaseService<Organization> {
    @Autowired
    private OrganizationMapper organizationMapper;

    @Transactional(readOnly = true)
    public List<ZTreeOrganizationVo> findChildren(Map<String, Object> params) {
        return organizationMapper.findChildren(params);
    }


    /**
     * 查找下级节点数量
     *
     * @param parentId
     * @return
     */
    @Transactional(readOnly = true)
    public int findChildrenCount(Long parentId) {
        Example example = new Example(Organization.class);
        example.createCriteria().andEqualTo("parentId", parentId);
        int count = organizationMapper.selectCountByExample(example);
        return count;
    }

    /**
     * 节点排序
     *
     * @param id1
     * @param id2
     */
    public void sort(Long id1, Long id2) {
        Organization organization1 = organizationMapper.selectByPrimaryKey(id1);
        Organization organization2 = organizationMapper.selectByPrimaryKey(id2);
        Long sort = organization1.getSort();
        organization1.setSort(organization2.getSort());
        organization2.setSort(sort);
        organizationMapper.updateByPrimaryKeySelective(organization1);
        organizationMapper.updateByPrimaryKeySelective(organization2);
    }

    /**
     * 保存记录
     */
    public void save(Organization organization) {
        this.insert(organization);
        organization.setSort(organization.getId());
        this.updateByPrimaryKeySelective(organization);
    }
}
